﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using X23.Application.Dto;
using X23.Util.SerializationUtil;

namespace X23.Extensions.FilterExtensions
{
    public class ResponseFilter : IAsyncResultFilter
    {
        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            if (context.Result is FileContentResult)
            {

            }
            else
            {
                var response = new ResponseDto
                {
                    Code = context.HttpContext.Response.StatusCode
                };
                if (context.Result is ObjectResult)
                {
                    response.Data = (context.Result as ObjectResult).Value;
                }
                else if (context.Result is ForbidResult)
                {
                    response.Data = "您没有该权限！";
                    context.HttpContext.Response.StatusCode = response.Code = (int)System.Net.HttpStatusCode.Forbidden;
                }
                context.Result = new ObjectResult(response);
            }
            await next();
        }
    }
}
